'use strict';

const BaseController = require('./BaseController');
class RoomController extends BaseController {
  async index(){
    const { ctx, app } = this;
    if(ctx.query.num){
      try{
        let room =  await app.model.Room.findAll({where:{num:ctx.query.num}});
        if(room.length>0){
          ctx.body = {code:1,msg:"",data:room}
        }else{
          ctx.body = {code:1,msg:`查不到${ctx.query.num}这个房间号`};
        }
      }catch(e){
        this.consoleError(e,ctx.query)
        ctx.body = {code:0,msg:"查询失败"}
      }
    }else{
      ctx.body = {code:0,msg:"请输入房间号进入房间"}
    }
  }
  async create() {
    const { ctx, app } = this;
    const params  = ctx.request.body;
    if(params.name && params.game_num){
      let res = this.checkInput({form:params,bean:"room"});
      if(res.code===0){
        ctx.body = res;
        return;
      }
      let room = {};
      let roomDetail = {};
      room.owners = params.user_name
      room.owners_id = params.user_id
      room.name = params.name
      room.game_num = params.game_num;
      room.id = this.getUUID();
      // room.create_time = this.parseTime(Date.now());
      // room.update_time = room.createTime;
      let currentTime = Date.now().toString();
      room.num = currentTime.substring(currentTime.length-6);
      roomDetail.room_name = room.name;
      roomDetail.room_id = room.id;
      roomDetail.user_id = room.owners_id
      roomDetail.user_name = room.owners;
      // roomDetail.create_time =room.createTime
      roomDetail.room_num = room.num;
      roomDetail.is_owners = true;
      try{
        const isExist = await app.model.Room.count({where:{owners_id:room.owners_id}});
        if(isExist>0){
          ctx.body = {code:0,msg:"不要重复创建房间！"};
          return;
        }
        // const result = await app.Sequelize.connection.transaction(async (t) => {
          await app.model.Room.create(room);
          await app.model.RoomDetail.create(roomDetail);
          roomDetail.game_num = room.game_num;
          ctx.body = {code:1,msg:"创建成功",data:roomDetail};
        // });
      }catch(e){
        this.consoleError(e,params)
        ctx.body = {code:0,msg:"创建房间异常"}
      }
    }else{
      ctx.body = {code:0,msg:"参数不正确"}
    }
    
  }
  async update(){
    const { ctx, app } = this;
  }
  async destroy(){
    const { ctx, app } = this;
  }
}

module.exports = RoomController;
